/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.terramagnet.pdmviewer.web;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author terrason
 */
@Service
public class FileStore {

	@Autowired
	private ServletContext context;

	/**
	 * 获取文件存储根目录.
	 */
	public File root() {
		String rootPath = context.getRealPath("/download");
		return new File(rootPath);
	}

	public File get(String checksum) {
		if (StringUtils.isBlank(checksum)) {
			return null;
		}
		File f = new File(root(), checksum);
		return f.exists() ? f : null;
	}

	public String save(MultipartFile file) throws IOException {
		String checksum = DigestUtils.md5DigestAsHex(file.getBytes());
		File dest = new File(root(), checksum);
		if (!dest.exists()) {
			file.transferTo(dest);
		}
		return checksum;
	}
}
